/**
 * 数据树形组件
 */
import React, { Component, Fragment } from 'react';
import { Tree, Spin, Popover, Divider, Tooltip, Popconfirm, Icon } from 'antd';
import { isEmpty, doActionHandler, ajax, buildTreeNodes, getLocalMessage,uniqueArray } from '../common';
import UIIcon from './UIIcon';
const TreeNode = Tree.TreeNode;

export default class UIDataTree extends Component {

    constructor(props) {
        super(props);

        const expandedTreeNodeIds = [];
        const checkedNodeIds = [];

        this.state = {
            loading: false,
            treeData: [],
            selectedNodeIds: [],
            expandedNodeIds: expandedTreeNodeIds,
            checkedNodeIds: checkedNodeIds,
            nodeActions: {},
            actionMenuVisible: true,
            defaultCheckedKeys:[],
            defaultExpandAll: false,
            treeShow : true,
            multiple : false,
            params: {},
        };
    }

    componentWillUnmount() {
        this._mounted = false
    }

    componentDidMount() {
        this._mounted = true;

        const { expandedNodeIds, checkedNodeIds } = this.state;

        const { dataUrl, pathValue,expandLevel,params } = this.props;
        
        let treeDataUrl = null;

        if (pathValue !== undefined) {
            treeDataUrl = dataUrl  + pathValue + '/';
        }
        else {
            treeDataUrl = dataUrl;
        }

        //拼接属性传递进来的参数
        let param = {};
        if(params !== undefined){
            param = {expandLevel: expandLevel,...params};
        }else{
            param = {expandLevel: expandLevel};

        }

        buildTreeNodes(treeDataUrl, param, (subNodes) => {
            
            this.getDefaultExpandNodeIds(subNodes, expandedNodeIds);
            if (this.props.checkable === true) {
                this.getDefaultCheckNodeIds(subNodes, checkedNodeIds);
            }

            this.setState({treeData: subNodes, expandedNodeIds: expandedNodeIds, checkedNodeIds: uniqueArray([...checkedNodeIds]) });
        });
    }

    handleActionMenuVisibleChange = (actionMenuVisible) => {
        //console.log(actionMenuVisible,obj);
        //this.setState({ actionMenuVisible });
    }

    getDefaultCheckNodeIds = (subNodes, checkedNodeIds) => {
        if(subNodes === null || subNodes === undefined){
            return;
        }
        for (let i = 0; i < subNodes.length; i++) {
            if (subNodes[i].state.checked === true) {
                checkedNodeIds.push(subNodes[i].id);
            }
            if (subNodes[i].nodes !== null) {
                this.getDefaultCheckNodeIds(subNodes[i].nodes, checkedNodeIds);
            }
        }

        //console.log(checkedNodeIds);
    }
    //搜索时选中
    getDefaultCheckedKeys = (subNodes, defaultCheckedKeys) => {
        if(subNodes === null || subNodes === undefined){
            return;
        }
        for (let i = 0; i < subNodes.length; i++) {
            if (subNodes[i].state.searched === true) {
                defaultCheckedKeys.push(subNodes[i].id);
                this.setState({
                    defaultCheckedKeys : defaultCheckedKeys
                })
            }
            if (subNodes[i].nodes !== null) {
                this.getDefaultCheckedKeys(subNodes[i].nodes, defaultCheckedKeys);
            }
        }
    }

    getDefaultExpandNodeIds = (subNodes, expandedTreeNodeIds) => {
        if(subNodes === null || subNodes === undefined){
            return;
        }
        for (let i = 0; i < subNodes.length; i++) {
            if (subNodes[i].expanded === true) {
                expandedTreeNodeIds.push(subNodes[i].id);
            }
            if (subNodes[i].nodes && subNodes[i].nodes.length > 0) {
                this.getDefaultExpandNodeIds(subNodes[i].nodes, expandedTreeNodeIds);
            }
        }
    }

    loadData = (params = {}) => {

        const { dataUrl, pathValue, expandLevel } = this.props;

        let treeDataUrl = null;
        let defaultCheckedKeys = []
        defaultCheckedKeys.length = 0
        if (pathValue !== undefined) {
            treeDataUrl = dataUrl  + pathValue + '/';
        }
        else {
            treeDataUrl = dataUrl;
        }

        //拼接属性传递进来的参数
        const porpsParams = this.props.params;
        let porpsParam = {};
        if(porpsParams !== undefined){
            porpsParam = {...porpsParams};
        }else{
            porpsParam = {};
        }
        const expandedTreeNodeIds = [];

        const checkedNodeIds = [];

        this.setState({ loading: true, nodeActions: {} });

        const treeParams = { expandLevel: expandLevel };
        this.setState({
            treeShow : false,
            multiple : false
        })
        setTimeout(function(){
            buildTreeNodes(treeDataUrl, { ...treeParams, ...params,...porpsParam }, (subNodes) => {
            
                this.getDefaultExpandNodeIds(subNodes, expandedTreeNodeIds);
                this.getDefaultCheckedKeys(subNodes, defaultCheckedKeys);
                if (this.props.checkable === true) {
                    this.getDefaultCheckNodeIds(subNodes, checkedNodeIds);
                }
                this.setState({
                    defaultCheckedKeys : defaultCheckedKeys
                })
                this.setState({ loading: false,treeData: subNodes, expandedNodeIds: expandedTreeNodeIds, checkedNodeIds: uniqueArray([...this.state.checkedNodeIds,...checkedNodeIds]) });
                this.setState({
                    treeShow : true,
                    multiple : true
                })
                this.setState(() => ({ multiple: false }));
                // setTimeout(function(){
                //     this.setState({
                //         multiple : false
                //     })
                // }.bind(this))
            });
        }.bind(this))

    }

    searchData = (params = {}) => {
        this.loadData({ ...params });
    }

    onLoadData = (treeNode) => {

        const { selectedNodeIds } = this.state;

        const { dataUrl, pathValue, expandLevel,params } = this.props;

        let treeDataUrl = null;

        if (pathValue !== undefined) {
            treeDataUrl = dataUrl  + pathValue + '/';
        }
        else {
            treeDataUrl = dataUrl;
        }

        //拼接属性传递进来的参数
        let param = {};
        if(params !== undefined){
            param = {...params};
        }else{
            param = {};
        }
        return new Promise((resolve) => {

            setTimeout(() => {
                const parentNode = treeNode.props.dataRef;
                const expandedNodeIds = [];
                const checkedNodeIds = [];
                buildTreeNodes(treeDataUrl, { ...param,n_level: parentNode.level, expandLevel: expandLevel, nodeid: parentNode.id, nodeConfigId: parentNode.nodeConfigId, selectedNodeId: selectedNodeIds }, (subNodes) => {
                    parentNode.nodes = subNodes;

                    if(subNodes.length > 0){
                        this.getDefaultExpandNodeIds(subNodes, expandedNodeIds);
                        if (this.props.checkable === true) {
                            this.getDefaultCheckNodeIds(subNodes, checkedNodeIds);
                        }

                        this.setState({
                            treeData: [...this.state.treeData],
                            expandedNodeIds: [...expandedNodeIds],
                            checkedNodeIds: uniqueArray([...this.state.checkedNodeIds,...checkedNodeIds]),
                        });
                    }

                    resolve();
                                       
                });
                
            });
           
        });
    }

    setSelectedRowKeys = (selectedKeys, node) => {
        this.setState({ selectedNodeIds: selectedKeys });
    }

    onTreeNodeSelect = (selectedKeys, e) => {
        if (e.selected === false) {
            return;
        }
        this.setState({ selectedNodeIds: selectedKeys});
        const { node } = e;
        if (this.props.onSelectChange !== undefined) {
            this.props.onSelectChange(selectedKeys, node);
        }
    }

    getSelectedNodeIds = () => {
        return this.state.selectedNodeIds;
    }

    clearSelectedNodeIds = () => {
        this.setState({ selectedNodeIds: [] });
    }

    handleNodeAction = (nodeAction, node) => {
        const { history, actionHandler, parent } = this.props;
        const actionEvent = {
            actionId: nodeAction.actionId,
            action: nodeAction.handler,
            component: parent != null ? parent : this,
            params: node
        };
        if (actionHandler !== undefined) {
            if (nodeAction.handler.startsWith('/') && history) {
                history.push(nodeAction.handler, node);
            }
            else {
                doActionHandler(actionEvent, actionHandler(actionEvent));
            }
        }
    }

    onNodeExpand = (expandedKeys, expanded, node) => {
        this.setState({ expandedNodeIds: expandedKeys });
    }

    renderTreeNodes = (data) => {

        const { renderTreeNode, currentModule } = this.props;
        const { nodeActions } = this.state;
        var owner = this;
        if (this._mounted === false) {
            return null;
        }
        else {

            return data.map((item) => {
                let nodeTitle = null;
                let nodeAction = null;
                if (item.actionGroupId) {
                    if (item.id in nodeActions) {
                        nodeAction = nodeActions[item.id];
                    }
                    else if (currentModule !== undefined) {

                        ajax('SYSTEM/auth/getUserActionGroupBean', { modelId: currentModule.menuId, actionGroupId: item.actionGroupId }, (actionGroup) => {
                            const cellActions = [];

                            if (actionGroup.actionBeans !== undefined) {
                                actionGroup.actionBeans.forEach((nodeAction, index, arr) => {
                                    let cellActionLink = null;
                                    if (isEmpty(nodeAction.desc) === false) {
                                        cellActionLink = <Tooltip mouseLeaveDelay={0} title={nodeAction.desc}>{isEmpty(nodeAction.confirmInfoKey) ? <a onClick={owner.handleNodeAction.bind(owner, { actionId: nodeAction.id, handler: nodeAction.handler }, item)}>{nodeAction.label}</a> : <a>{nodeAction.label}</a>}{index < arr.length - 1 ? <Divider type="vertical" /> : ''}</Tooltip>
                                    }
                                    else {
                                        cellActionLink = <Fragment>{isEmpty(nodeAction.confirmInfoKey) ? <a onClick={owner.handleNodeAction.bind(owner, { actionId: nodeAction.id, handler: nodeAction.handler }, item)}>{nodeAction.label}</a> : <a>{nodeAction.label}</a>}{index < arr.length - 1 ? <Divider type="vertical" /> : ''}</Fragment>
                                    }

                                    if (isEmpty(nodeAction.confirmInfoKey) === false) {
                                        cellActions.push(<Popconfirm key={item.id} title={getLocalMessage(nodeAction.confirmInfoKey)} onConfirm={owner.handleNodeAction.bind(owner, { actionId: nodeAction.id, handler: nodeAction.handler }, item)}>{cellActionLink}</Popconfirm>);
                                    }
                                    else {
                                        cellActions.push(<Fragment key={item.id}>{cellActionLink}</Fragment>);
                                    }
                                });
                            }

                            nodeAction = (<Popover placement="bottom" content={cellActions} onVisibleChange={owner.handleActionMenuVisibleChange}><Icon type="setting" /></Popover>);
                            nodeActions[item.id] = nodeAction;
                            owner.setState(nodeActions);
                        });
                    }
                }
                if (renderTreeNode) {
                    nodeTitle = (<span style={{color:(item.nodeData.status === 1 ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 0, 0, 0.65)")}}><UIIcon icon={item.icon}></UIIcon> {renderTreeNode(item)} {nodeAction}</span>);
                }
                else {
                    nodeTitle = (<span style={{color:(item.nodeData.status === 1 ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 0, 0, 0.65)")}}><UIIcon icon={item.icon} ></UIIcon> {item.text} {nodeAction}</span>);
                }
                if (item.nodes && item.nodes.length > 0) {
                    return (
                        <TreeNode icon={<UIIcon icon={item.icon} ></UIIcon>} title={nodeTitle} key={item.id} isLeaf={item.isLeaf} dataRef={item}>
                            {this.renderTreeNodes(item.nodes)}
                        </TreeNode>
                    );
                }
                else {
                    return <TreeNode title={nodeTitle} key={item.id} isLeaf={item.isLeaf} dataRef={item} />;
                }

            });
        }
    }

    onCheck = (checkedKeys,e) => {
        //console.log('onCheck', checkedKeys);
        this.setState({checkedNodeIds : checkedKeys.checked });
        if(this.props.onCheck !== undefined){
            this.props.onCheck(checkedKeys,e);
        }
    }

    render() {
        return (
            <Spin spinning={this.state.loading}>
                {
                    this.state.treeData.length > 0 && this.state.treeShow ? (
                        <Tree loadData={this.onLoadData} showIcon={false}
                            defaultCheckedKeys={this.state.checkedNodeIds}
                            checkedKeys={this.state.checkedNodeIds}
                            defaultExpandedKeys={this.state.expandedNodeIds}
                            defaultExpandAll={this.props.expandLevel === -1}
                            multiple={this.state.multiple}
                            draggable
                            defaultSelectedKeys={this.state.defaultCheckedKeys}
                            onSelect={this.onTreeNodeSelect}
                            onExpand={this.onNodeExpand}
                            checkable={this.props.checkable}//注意：和checkStrictly属性组合使用
                            onCheck={this.onCheck}
                            checkStrictly={this.props.checkStrictly}
                        >
                            {this.renderTreeNodes(this.state.treeData)}
                        </Tree>
                    ) : null
                }
                {/* {
                    this.state.treeData.length > 0 && this.state.defaultCheckedKeys.length == 0 ? (
                        <Tree loadData={this.onLoadData} showIcon={false}
                            //defaultCheckedKeys={this.state.checkedNodeIds}
                            // checkedKeys={this.state.checkedNodeIds}
                            // defaultExpandedKeys={this.state.expandedNodeIds}
                            // defaultExpandAll={this.props.expandLevel === -1}
                            defaultExpandAll={true}
                            // multiple
                            defaultSelectedKeys={this.state.defaultCheckedKeys}
                            // onSelect={this.onTreeNodeSelect}
                            // onExpand={this.onNodeExpand}
                            // checkable={this.props.checkable}
                            // onCheck={this.onCheck}
                            // checkStrictly={this.props.checkStrictly}
                        >
                            {this.renderTreeNodes(this.state.treeData)}
                        </Tree>
                    ) : null
                }
                 {
                    this.state.defaultCheckedKeys.length > 0 ? (
                        <Tree loadData={this.onLoadData} showIcon={false}
                            //defaultCheckedKeys={this.state.checkedNodeIds}
                            // checkedKeys={this.state.checkedNodeIds}
                            // defaultExpandedKeys={this.state.expandedNodeIds}
                            // defaultExpandAll={this.props.expandLevel === -1}
                            defaultExpandAll={true}
                            multiple
                            defaultSelectedKeys={this.state.defaultCheckedKeys}
                            // onSelect={this.onTreeNodeSelect}
                            // onExpand={this.onNodeExpand}
                            // checkable={this.props.checkable}
                            // onCheck={this.onCheck}
                            // checkStrictly={this.props.checkStrictly}
                        >
                            {this.renderTreeNodes(this.state.treeData)}
                        </Tree>
                    ) : null
                } */}
            </Spin >
        );
    }
}
